<template>
  <div class="admin-management">
    <h2>管理员管理</h2>
    <!-- 管理员类型切换 -->
    <div class="actions">
      <el-radio-group v-model="adminType" @change="fetchAdmins">
        <el-radio-button label="系统管理员">系统管理员</el-radio-button>
        <el-radio-button label="图书管理员">图书管理员</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 搜索区域 -->
    <div class="actions">
      <el-input
          v-model="search.username"
          placeholder="输入用户名搜索"
          style="width: 200px; margin-right: 10px"
      />
      <el-input
          v-model="search.name"
          :placeholder="adminType === '系统管理员' ? '输入管理员姓名搜索' : '输入图书管理员姓名搜索'"
          style="width: 200px; margin-right: 10px"
      />
      <el-select
          v-model="search.status"
          placeholder="选择账户状态"
          style="width: 150px; margin-right: 10px"
          @change="fetchAdmins"
      >
        <el-option label="全部" :value="-1" />
        <el-option label="正常" :value="1" />
        <el-option label="禁用" :value="0" />
      </el-select>
      <el-button type="primary" @click="fetchAdmins">搜索</el-button>
    </div>

    <!-- 操作区域 -->
    <div class="actions">
      <el-button type="danger" :disabled="selectedAdmins.length === 0" @click="batchDeleteAdmins">删除</el-button>
      <el-button type="warning" :disabled="selectedAdmins.length === 0" @click="batchUpdateStatus(0)">禁用</el-button>
      <el-button type="success" :disabled="selectedAdmins.length === 0" @click="batchUpdateStatus(1)">启用</el-button>
      <el-button type="primary" @click="openDialog">添加管理员</el-button>
    </div>

    <!-- 管理员表格 -->
    <el-table
        :data="adminData.content"
        style="width: 100%"
        :height="450"
        row-key="id"
        v-loading="loading"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column type="index" label="序号" width="60" :index="indexMethod" />
      <el-table-column :prop="adminType === '系统管理员' ? 'adminId' : 'bookAdminId'" label="管理员ID" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column :prop="adminType === '系统管理员' ? 'adminName' : 'bookAdminName'" label="姓名" />
      <el-table-column prop="email" v-if="adminType === '图书管理员'" label="邮箱" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="() => editAdmin(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-actions">
      <el-pagination
          background
          layout="prev, pager, next, sizes, total, jumper"
          :total="adminData.totalElements"
          :page-size="pagination.size"
          v-model:current-page="pagination.page"
          @update:currentPage="fetchAdmins"
          @size-change="handleSizeChange"
      />
    </div>
    <!-- 添加/编辑管理员弹窗 -->
    <el-dialog title="管理员信息" v-model="dialogVisible" width="400px">
      <el-form :model="formData">
        <el-form-item label="用户名" required>
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" :required="!formData.id">
          <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="姓名" required>
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item v-if="adminType === '图书管理员'" prop="email" label="邮箱" required :rules="[{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        }, {
          type: 'email',
          message: '请输入正确的邮箱格式',
          trigger: ['blur', 'change']
        }]">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAdmin">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, shallowRef } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { debounce } from 'lodash-es';
import http from '../utils/axios';

const adminType = ref('系统管理员'); // 当前管理员类型
const adminData = ref({ content: [], totalElements: 0 });
const pagination = ref({ page: 1, size: 10 });
const search = ref({ username: '', name: '', status: -1 });
const selectedAdmins = shallowRef([]);
const dialogVisible = ref(false);
const formData = ref({ id: '', username: '', password: '', name: '', email: '' });
const loading = ref(false);

const indexMethod = (index) => index + 1;

const getApiPath = (action) => {
  const pathMap = {
    all: adminType.value === '系统管理员' ? '/adminManage/admins/all' : '/adminManage/bookAdmins/all',
    register: adminType.value === '系统管理员' ? '/adminManage/admins/create' : '/adminManage/bookAdmins/create',
    delete:
        adminType.value === '系统管理员'
            ? `/adminManage/admin/batch/delete`
            : `/adminManage/bookAdmins/batch/delete`,
  };
  return pathMap[action];
};

const fetchAdmins = debounce(async () => {
  loading.value = true;
  try {
    const { username, name, status } = search.value;
    const queryStatus = status === -1 ? null : status;
    // 动态设置姓名字段的 key
    const nameField = adminType.value === '系统管理员' ? 'adminName' : 'bookAdminName';
    // 请求数据
    const response = await http.post(getApiPath('all'), {
      page: pagination.value.page - 1,
      size: pagination.value.size,
      username: username || undefined,
      [nameField]: name || undefined, // 动态映射字段
      status: queryStatus,
    });
    adminData.value = response.data || { content: [], totalElements: 0 };
  } catch (error) {
    ElMessage.error('获取管理员列表失败：' + error.message);
  } finally {
    loading.value = false;
  }
}, 300);

const saveAdmin = async () => {
  try {
    const apiPath =
        formData.value.id
            ? (adminType.value === '系统管理员'
                ? `/adminManage/admins/update/${formData.value.id}`
                : `/adminManage/bookAdmins/update/${formData.value.id}`)
            : (adminType.value === '系统管理员'
                ? '/adminManage/admins/create'
                : '/adminManage/bookAdmins/create');

    const method = formData.value.id ? 'put' : 'post';
    // 根据管理员类型动态构建请求数据
    const requestData = {
      username: formData.value.username,
      password: formData.value.password,
      ...(adminType.value === '系统管理员'
          ? { adminName: formData.value.name }
          : {
            bookAdminName: formData.value.name,
            email: formData.value.email,
          }),
    };
    // 发送请求
    await http[method](apiPath, requestData);
    ElMessage.success('管理员信息保存成功！');
    dialogVisible.value = false;
    await fetchAdmins();
  } catch (error) {
    ElMessage.error('保存失败：' + error.message);
  }
};

const editAdmin = (admin) => {
  dialogVisible.value = true;
  formData.value = {
    id: adminType.value === '系统管理员' ? admin.adminId : admin.bookAdminId,
    username: admin.username,
    password: null, // 密码默认空，需要用户重新填写
    name: adminType.value === '系统管理员' ? admin.adminName : admin.bookAdminName,
    email: admin.email || '',
  };
};

const batchDeleteAdmins = async () => {
  try {
    await ElMessageBox.confirm("确定要删除选中的管理员吗？", "提示", {
      type: "warning",
    });
    const apiPath =
        adminType.value === "系统管理员"
            ? "/adminManage/admins/batch/delete"
            : "/adminManage/bookAdmins/batch/delete";
    const idField =
        adminType.value === "系统管理员" ? "adminIds" : "bookAdminIds";

    const ids = selectedAdmins.value
        .map((admin) =>
            adminType.value === "系统管理员" ? admin.adminId : admin.bookAdminId
        )
        .filter(Boolean);
    if (ids.length === 0) {
      ElMessage.warning("请选择至少一个管理员进行操作！");
      return;
    }

    await http.delete(apiPath, {
      data: {
        [idField]: ids,
      },
    });
    ElMessage.success("删除成功！");
    await fetchAdmins();
  } catch (error) {
    ElMessage.error("删除失败：" + error.message);
  }
};

const batchUpdateStatus = async (status) => {
  try {
    const apiPath =
        adminType.value === "系统管理员"
            ? "/adminManage/admins/batch/status"
            : "/adminManage/bookAdmins/batch/status";
    const idField =
        adminType.value === "系统管理员" ? "adminIds" : "bookAdminIds";

    const ids = selectedAdmins.value
        .map((admin) =>
            adminType.value === "系统管理员" ? admin.adminId : admin.bookAdminId
        )
        .filter(Boolean);

    if (ids.length === 0) {
      ElMessage.warning("请选择至少一个管理员进行操作！");
      return;
    }

    await http.put(apiPath, {
      [idField]: ids,
      status,
    });

    ElMessage.success("状态更新成功！");
    await fetchAdmins();
  } catch (error) {
    ElMessage.error("状态更新失败：" + error.message);
  }
};

onMounted(fetchAdmins);
const handleSelectionChange = (val) => {
  selectedAdmins.value = val;
};
const handleSizeChange = (val) => {
  pagination.value.size = val;
  fetchAdmins();
};
const openDialog = () => {
  dialogVisible.value = true;
  formData.value = {
    id: '',
    username: '',
    password: '',
    name: '',
    email: ''
  };
};
</script>

<style scoped>
.admin-management {
  padding: 20px;
}

.actions {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.pagination-actions el-input,
.pagination-actions el-button {
  margin-right: 10px;
}
</style>
